import * as THREE from 'three'
import { FreeThree } from './FreeThree.js'
export function initScene(context, inputElement) {
    inputElement = inputElement || context.canvas

    const renderer = new THREE.WebGLRenderer({ antialias: true, ...context })

    const fov = 30
    const aspect = inputElement.clientWidth / inputElement.clientHeight
    const near = 0.1
    const far = 10000000000
    const camera = new THREE.PerspectiveCamera(fov, aspect, near, far)

    const scene = new THREE.Scene()

    scene.my = {
        renderer,
        camera,
        preRender: [],
        postRender: [],
        cafId: null,
        destroy() {
            cancelAnimationFrame(scene.my.cafId)
            requestAnimationFrame(() => {
                FreeThree.disposeObject3D(scene)
                scene.my = null
            })
        },
    }

    function resizeRendererToDisplaySize(renderer) {
        const pixelRatio = self.importScripts
            ? inputElement.devicePixelRatio
            : window.devicePixelRatio
        const width = Math.floor(inputElement.clientWidth * pixelRatio)
        const height = Math.floor(inputElement.clientHeight * pixelRatio)

        const canvas = renderer.domElement
        const needResize = canvas.width !== width || canvas.height !== height
        if (needResize) {
            renderer.setSize(width, height, false)
        }
        return needResize
    }
    let i = 0
    function render(time) {
        const { camera } = scene.my
        if (resizeRendererToDisplaySize(renderer)) {
            camera.aspect = inputElement.clientWidth / inputElement.clientHeight
            camera.updateProjectionMatrix()
        }

        scene.my.preRender.forEach((callback) => callback(time))
        renderer.render(scene, camera)
        scene.my.postRender.forEach((callback) => callback(time))

        // console.log(i)
        scene.my.cafId = requestAnimationFrame(render)
    }

    scene.my.cafId = requestAnimationFrame(render)

    return scene
}
